<?php
namespace Secret\Services;

class GenericSP implements \Silex\ServiceProviderInterface {

	protected $app;

	public function register(\Silex\Application $app, array $options = array()) {
		$app['generic'] = $this;
		$this->app = $app;
	}

	public function boot(\Silex\Application $app) {}

	public function data($entity, $whereDql = '', $params = array(), $options = array()) {
		$qb = $this->app['em']->createQueryBuilder();
		$qb->from("Secret\\Entities\\$entity", 'entity')->select('entity');
		if (! empty($whereDql)) {
			$qb->where($whereDql);
		}
		if (count($params) > 0) {
			$qb->setParameters($params);
		}
		if (isset($options['sort']) && isset($options['order'])) {
			$qb->orderBy("entity." . $options['sort'], $options['order']);
		}
		if (isset($options['page']) && isset($options['limit'])) {
			$qb->setFirstResult(($options['page'] - 1) * $options['limit']);
			$qb->setMaxResults($options['limit']);
		}
		return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
	}
	
	public function modelData($modelName, $whereDql = '', $params = array(), $options = array()) {
		$repo = $this->app['em']->getRepository('Secret\Entities\Content');
		$model = $repo->model($modelName);
		return $repo->data($model, $whereDql, $params, $options);
	}
}